(function() {
  const HOST_URL = '';

  function createErrorObject(err) {
    return new Error(err);
  }

  function ajaxGet(url, query) {
    return new Promise(function(resolve, reject) {
      return $.ajax({
        url: HOST_URL + url,
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json',
        data: query || {}
      }).done(resolve).fail(err => {
        reject(createErrorObject(err));
      });
    });
  }

  function ajaxPost(url, query, data) {
    return new Promise((resolve, reject) => {
      let aQuery = Object.keys(query).map(key => {
        return `${key}=${encodeURIComponent(query[key])}`;
      });

      $.ajax({
        url: HOST_URL + url + (aQuery.length > 0 ? `?${aQuery.join('&')}` : ''),
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data)
      }).done(resolve).fail(err => {
        reject(createErrorObject(err));
      });
    });
  }


  window.hackthon = {
    getBosses: function() {
      return ajaxGet('/game/bosses');
    },
    getUsers: function() {
      return ajaxGet('/game/players');
    },
    getBattles: function(boss_id, event_id) {
      return ajaxGet('/game/battles', {
        boss_id: boss_id,
        event_id: event_id
      });
    },
    attack: function(boss_id, player_id) {
      return ajaxPost('/game/battle', {
        boss_id: boss_id,
        player_id: player_id
      });
    },
    joinGroup: function(user_id) {
      return ajaxPost('/game/join', {
        player_id: user_id,
        group_id: 1
      });
    },
    rebirth: function(boss_id) {
      return ajaxPost('/game/reborn', {
        boss_id: boss_id
      });
    }

  };
}());